package src.DAO;

import src.jdbc.PostgreSQL;
import src.Entities.Telefono;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
/**
 *
 * @author Rodrigo
 */
public class TelefonoDAO {

    public String deleteTelefono(int telefonoID){
        try {
            String sql = "DELETE FROM telefono WHERE telefono_id = ?;";
            PreparedStatement delete = PostgreSQL.getConnection().prepareStatement(sql);
            delete.setInt(1, telefonoID);
            return String.valueOf(delete.execute());
        } catch (Exception e) {
            return e.toString();
        }
    }

    public String insertTelefono(Telefono phone) {
        try {
            String sql = "INSERT " +
                    "       INTO usuario(telefono_id, numero, cod_area, cod_pais, persona_id)" +
                    "     VALUES (NEXTVAL('telefono_seq'), ?,?,?,?)";
            PreparedStatement insert = PostgreSQL.getConnection().prepareStatement(sql);
            insert.setString(1, phone.getNumero());
            insert.setString(2, phone.getCodArea());
            insert.setString(3, phone.getCodPais());
            insert.setInt(4, phone.getPersonaId());
            return String.valueOf(insert.execute());
        } catch (Exception e) {
            return e.toString();
        }
    }

    public ArrayList selectTelefono(String sql) {
        ArrayList results = new ArrayList();
        try {
            Connection con = PostgreSQL.getConnection();
            Statement select = con.createStatement();
            ResultSet query = select.executeQuery(sql);
            while (query.next()) {
                Telefono phone = new Telefono(query.getInt("telefono_id"),
                        query.getString("numero"), query.getString("cod_area"),
                        query.getString("cod_pais"),query.getInt("persona_id"));
                results.add(phone);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return results;
    }

    public String updateTelefono(Telefono phone) {
        try {
            String sql = "UPDATE telefono" +
                    "        SET numero = ?, cod_area = ?, cod_pais = ?, persona_id = ?" +
                    "      WHERE telefono_id = ?";
            PreparedStatement update = PostgreSQL.getConnection().prepareStatement(sql);
            update.setString(1, phone.getNumero());
            update.setString(2, phone.getCodArea());
            update.setString(3, phone.getCodPais());
            update.setInt(4, phone.getPersonaId());
            update.setInt(5, phone.getTelefonoId());
            return String.valueOf(update.execute());
        } catch (Exception e) {
            return e.toString();
        }
    }
}
